package fr.imag.adele.mediation.probes.impl;

import java.util.Date;
import java.util.Hashtable;
import java.util.Random;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.util.tracker.ServiceTracker;

public class CpuProbe extends Thread implements BundleActivator{
	private Hashtable 		m_dataInfo = new Hashtable();	
	private ServiceTracker 	m_tracker;
	
	private BundleContext 	m_bundleContext;			
	private EventAdmin 		ea;
	private boolean 		m_working;
	
	public CpuProbe() { super("Cpu Probe"); }
	
	public void start(BundleContext bc) throws Exception {
		m_tracker = new ServiceTracker(bc, EventAdmin.class.getName(), null);
		m_tracker.open();
		start();				
	}

	public void stop(BundleContext arg0) throws Exception {		
		interrupt();
		m_tracker.close();
	}

	public void run() {
		while(! Thread.interrupted()) {			
			try {	
				Random r = new Random(System.currentTimeMillis());
				int cpu = r.nextInt() % 100;
				m_dataInfo.put("cp.event.resource", new String("cpu"));
				m_dataInfo.put("cp.event.source", new String("cpu1"));
				m_dataInfo.put("cp.event.timestamp", new Date().toString());
				m_dataInfo.put("cp.event.value", String.valueOf(Math.abs(cpu)));
				m_dataInfo.put("cp.event.unit", new String("%"));
				
				EventAdmin ea = (EventAdmin)m_tracker.getService();
				if (ea != null) {
					ea.sendEvent(new Event("cpu1/cpu",m_dataInfo));
					System.out.println("[CPU PROBE] Sending... (cpu1/cpu)");
				}				
				Thread.sleep(2000);
				
			} catch (InterruptedException e) {
				// no thing.
			}
		}/*
		while(m_working == true){
			System.out.println("[CPU PROBE].");
			if (ea != null){
				DataEvent dataEvent = new DataEvent("cpu", "cpu1", "11:39:54", "34", "%", null);
				ea.sendEvent(new Event("cpu1/cpu", dataEvent.getData()));
				System.out.println("[CPU PROBE] Sending... (" + dataEvent.getSource()+"/"+dataEvent.getResource() + ")");
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
		}*/
	}
	
}
